# -*- coding: utf-8 -*-

# 引入http response
from django.http import HttpResponse
from django.http import JsonResponse
import json
# 引入鉴权模块
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.models import User
# 引入token模块
import vue_app.utils.token as Token
# 引入鉴权装饰器
from vue_app.utils.auth_permission import auth_permission_require


# request api
def login_api(request):
    data = json.loads(request.body)
    username = data.get("username", "")
    password = data.get("password", "")
    # 查询username数据是否在内置模型User中
    if User.objects.filter(username=username):
        # 验证账号密码
        user = authenticate(username=username, password=password)
        if user:
            # 成功了！
            print("登陆成功了", user.username)
            token = Token.token_encode(username=user.get_username())
            res = {"token": token, "code": 20000}
            # 调用login
            login(request, user)
            return JsonResponse(res)

    res = {"token": "", "code": 0}
    return JsonResponse(res)

@auth_permission_require('')
def getinfo_api(request):
    print(request.method)
    token = request.GET.get('token')
    print(token)
    data = {"name": "Hello", "avatar": "User", "code": 20000}
    return JsonResponse(data)


@auth_permission_require('')
def logout_api(request):
    print(request.method)
    logout(request)
    print("Request Logout")
    response = {"code": 20000}
    return JsonResponse(response)